package CCN::CallWeaver::generate;
# (c) 2007, Stephane Alnet
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
use strict; use warnings;

use CCN::Core::FileTools;
use configuration;

sub get_template($)
{
    my $what = shift;
    return CCN::Core::FileTools::content_of("$configuration::perl_base/CCN/CallWeaver/templates/$what");
}

sub print_config($$)
{
    my ($what,$content) = @_;
    CCN::Core::FileTools::print_to("$configuration::html_base/config/$what",$content);
}

sub run_sip($)
{
    my $T = shift;

    mkdir "$configuration::html_base/config/etc";
    mkdir "$configuration::html_base/config/etc/callweaver";

    # Generate sip.conf

    my @peers = CCN::CallWeaver::probe::peers();
    my @peer_names = map { $_->{peer_name} } @peers;

    my @sip_conf_peers = ();
    my @sip_registrations = ();
    
    for my $peer (@peer_names)
    {
        next unless defined $T->{"${peer}_mode"} and $T->{"${peer}_mode"} ne 'unused';

        my $hostname = $T->{"${peer}_hostname"};
        my $username = $T->{"${peer}_username"};
        my $password = $T->{"${peer}_password"};

        my $sip_conf_peer = <<EOT;
[$peer]
type=friend
context=from-$peer
disallow=all
allow=ulaw
allow=alaw
canreinvite=no
insecure=very
EOT
        my $sip_registration = '';

        if($hostname)
        {
            $sip_conf_peer .= <<EOT;
host=$hostname
EOT
        }

        if($username and $password)
        {
            $sip_conf_peer .= <<EOT;
username=$username
secret=$password
fromuser=$username
allowguest=yes
EOT
            $sip_registration .= <<EOT;
register => $username:$password\@$hostname/$peer
EOT
        }

        push @sip_conf_peers, $sip_conf_peer;
        push @sip_registrations, $sip_registration;
    }
    
    my $tmpl = new HTML::Template(
        filename => "$configuration::perl_base/CCN/CallWeaver/templates/sip.conf",
        die_on_bad_params => 0, global_vars => 1);
    $tmpl->param(
        authentication_entries => join("\n",@sip_registrations),
        peer_entries => join("\n",@sip_conf_peers),
    );
    print_config('etc/callweaver/sip.conf',$tmpl->output);

    # Everything went fine
    return '';
}

sub run_extensions($)
{
    my $T = shift;

    mkdir "$configuration::html_base/config/etc";
    mkdir "$configuration::html_base/config/etc/callweaver";

    # Generate extensions.conf

    my @targets = CCN::CallWeaver::probe::targets();
    my %target_dial = map { $_->{cr_name} => $_->{cr_dial} } @targets;

    my @extensions = ();

    for my $s (@targets)
    {
        my $extension = <<EOT;
[from-$s->{cr_source}]
EOT

        for my $callroute (CCN::CallWeaver::probe::_callroutes_names())
        {
            my $cr_name = "$s->{cr_name}_${callroute}";

            my $pattern = $T->{"${cr_name}_pattern"};
            $pattern = 'X.' if not defined $pattern or $pattern eq '';
            my $skip    = $T->{"${cr_name}_skip"} || 0;
            my $keep    = $T->{"${cr_name}_keep"};
            my $prepend = $T->{"${cr_name}_prepend"};
            $prepend = '' if not defined $prepend;
            my $target  = $T->{"${cr_name}_target"};

            next unless defined $target and $target ne '' and lc($target) ne 'unused';

            my $target_dial = $target_dial{$target};

            if($skip == 0)
            {
                $skip = '';
            }
            else
            {
                $skip = ":${skip}";
            }

            if(not defined $keep or $keep ne /^\d+$/)
            {
                $keep = '';
            }
            else
            {
                $keep = ":${keep}";
            }

            my $cw_pattern = $pattern =~ /[NX.]/ ? "_${pattern}" : $pattern;

            $extension .= <<EOT;
exten => ${cw_pattern},1,NoOp(Route item ${cr_name})
;exten => ${cw_pattern},n,SetTransferCapability(3K1AUDIO)
exten => ${cw_pattern},n,Dial(${target_dial}/${prepend}\${EXTEN${skip}${keep}})
EOT
        }

        push @extensions, $extension;
    }

    print_config('etc/callweaver/extensions.conf',get_template('extensions.conf').join("\n",@extensions));

    # Everything went fine
    return '';
}

1;